package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartIntercepter;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX="cart:";

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartIntercepter.threadLocal.get();
        Cart cart = new Cart();
        if (userInfoTo.getUserId() == null) {//没登陆，临时购物车
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            cart.setItems(getCartItems(cartKey));
            return cart;
        }
        //已登录
        //合并临时购物车
        List<CartItem> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
        if (tempCartItems != null) {
            for (CartItem item : tempCartItems) {
                addToCart(item.getSkuId(), item.getCount());
            }
            clearCart(CART_PREFIX + userInfoTo.getUserKey());
        }
        //登录后的购物车
        String cartKey = CART_PREFIX + userInfoTo.getUserId();
        List<CartItem> cartItems = getCartItems(cartKey);
        cart.setItems(cartItems);
        return cart;
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str=(String) cartOps.get(skuId.toString());
        return (CartItem)JSON.parseObject(str,CartItem.class);
    }

    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if(values!=null&&values.size()>0){
            List<CartItem> items = values.stream().map(obj -> {
                return JSON.parseObject((String) obj,CartItem.class);
            }).collect(Collectors.toList());
            return items;
        }
        return null;
    }

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps=getCartOps();
        String res = (String)cartOps.get(skuId.toString());
        if(StringUtils.isNotEmpty(res)){//购物车中已有
            CartItem citem = JSON.parseObject(res, CartItem.class);
            citem.setCount(citem.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(citem));
            return citem;
        }
        CartItem cartItem = new CartItem();
        CompletableFuture<Void> skuTask = CompletableFuture.runAsync(() -> {
            R r = productFeignService.getSkuInfo(skuId);
            SkuInfoVo info = (SkuInfoVo) r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
            });

            cartItem.setSkuId(skuId);
            cartItem.setCheck(true);
            cartItem.setCount(num);
            cartItem.setImage(info.getSkuDefaultImg());
            cartItem.setPrice(info.getPrice());
            cartItem.setTitle(info.getSkuTitle());
        }, executor);
        CompletableFuture<Void> attrTask = CompletableFuture.runAsync(() -> {
            List<String> attrs = productFeignService.getSkuSaleAttrValues(skuId);
            cartItem.setSkuAttr(attrs);
        }, executor);
        CompletableFuture.allOf(skuTask,attrTask).get();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
        return cartItem;
    }

    /**
     * 获取要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartIntercepter.threadLocal.get();
        String cartKey=CART_PREFIX;
        if(userInfoTo.getUserId()!=null){
            cartKey+=userInfoTo.getUserId();
        }else{
            cartKey+=userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartIntercepter.threadLocal.get();
        List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId());
        List<CartItem> collect = cartItems.stream()
                .filter(item -> item.getCheck())
                .map(item->{
                    R r=productFeignService.getPrice(item.getSkuId());
                    item.setPrice(new BigDecimal((String)r.get("data")));
                    return item;
                })
                .collect(Collectors.toList());
        return collect;
    }
}
